package cn.yangyumanage.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.yangyumanage.R;
import cn.yangyumanage.application.DataApplication;
import cn.yangyumanage.bean.EpisodeUrl;
import cn.yangyumanage.bean.Film;
import cn.yangyumanage.bean.FilmUrl;
import cn.yangyumanage.bean.ImageQuality;
import cn.yangyumanage.bean.LargeClassification;
import cn.yangyumanage.bean.SmallClassification;
import cn.yangyumanage.bean.TheRegion;
import cn.yangyumanage.bean.TheYear;
import cn.yangyumanage.callback.DataCallBack;
import cn.yangyumanage.http.HttpClient;
import cn.yangyumanage.model.FilmAddHttpModel;
import cn.yangyumanage.util.ToastUtil;
import cn.yangyumanage.util.Utils;

public class FilmAddFragment extends Fragment implements View.OnClickListener {


    private View view;
    private Context context;
    private EditText et_sid;
    private final FilmAddHttpModel httpModel = new FilmAddHttpModel();
    private Bundle bundle;
    private EditText et_film_name;
    private EditText et_tag;
    private EditText et_post_url;
    private EditText et_score;
    private EditText et_director;
    private EditText et_scriptwriter;
    private EditText et_leading_role;
    private EditText et_production_country_or_region;
    private EditText et_language;
    private EditText et_release_date;
    private EditText et_premiere;
    private EditText et_single_episode_length;
    private EditText et_number_of_seasons;
    private EditText et_number_of_episode;
    private EditText et_aka;
    private EditText et_plot;
    private EditText et_pinyin_name;
    private Spinner sp_large_classification;
    private Spinner sp_small_classification;
    private Spinner sp_the_year;
    private Spinner sp_the_region;
    private Spinner sp_image_quality;
    private EditText et_play_num;
    private EditText et_film_url;
    private Film film = new Film();
    private NestedScrollView nsv_film_add;
    private LinearLayout ll_url_quick_add;
    private EditText et_url_qianbu;
    private EditText et_url_weibu;
    private Gson gson = new GsonBuilder().serializeNulls().create();
    private LinearLayout ll_url_item_add;
    private ArrayList<Spinner> spinners = new ArrayList<>();
    private ArrayList<EditText> editTexts = new ArrayList<>();
    private LinearLayout ll_item_store;
    private ArrayAdapter<String> arrayAdapter;
    private LinearLayout ll_add;
    private TextView tv_status;
    private SmartRefreshLayout srl_film_add;
    private AVLoadingIndicatorView aiv_douban_search;


    public FilmAddFragment() {
    }

    public FilmAddFragment(Context context, AVLoadingIndicatorView aiv_douban_search) {
        this.context = context;
        this.aiv_douban_search = aiv_douban_search;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_film_add, container, false);
        initView();
        initData();
        return view;
    }

    private void initView() {
        et_sid = view.findViewById(R.id.et_sid);
        et_sid.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (et_sid.getText().toString().equals("")) {
                    tv_status.setText("");
                } else {
                    aiv_douban_search.smoothToShow();
                    querySidExists(et_sid.getText().toString());
                    getFilmDetails(et_sid.getText().toString());
                }
            }
        });
        et_film_name = view.findViewById(R.id.et_film_name);
        et_tag = view.findViewById(R.id.et_tag);
        et_post_url = view.findViewById(R.id.et_post_url);
        et_score = view.findViewById(R.id.et_score);
        et_director = view.findViewById(R.id.et_director);
        et_scriptwriter = view.findViewById(R.id.et_scriptwriter);
        et_leading_role = view.findViewById(R.id.et_leading_role);
        et_production_country_or_region = view.findViewById(R.id.et_production_country_or_region);
        et_language = view.findViewById(R.id.et_language);
        et_release_date = view.findViewById(R.id.et_release_date);
        et_premiere = view.findViewById(R.id.et_premiere);
        et_single_episode_length = view.findViewById(R.id.et_single_episode_length);
        et_number_of_seasons = view.findViewById(R.id.et_number_of_seasons);
        et_number_of_episode = view.findViewById(R.id.et_number_of_episode);
        et_aka = view.findViewById(R.id.et_aka);
        et_plot = view.findViewById(R.id.et_plot);
        et_pinyin_name = view.findViewById(R.id.et_pinyin_name);
        sp_large_classification = view.findViewById(R.id.sp_large_classification);
        sp_small_classification = view.findViewById(R.id.sp_small_classification);
        sp_the_year = view.findViewById(R.id.sp_the_year);
        sp_the_region = view.findViewById(R.id.sp_the_region);
        sp_image_quality = view.findViewById(R.id.sp_image_quality);
        et_play_num = view.findViewById(R.id.et_play_num);
        et_play_num.setText("0");
        ll_add = view.findViewById(R.id.ll_add);
        ll_add.setOnClickListener(this);
        et_film_url = view.findViewById(R.id.et_film_url);
        nsv_film_add = view.findViewById(R.id.nsv_film_add);
        ll_url_quick_add = view.findViewById(R.id.ll_url_quick_add);
        ll_url_quick_add.setOnClickListener(this);
        et_url_qianbu = view.findViewById(R.id.et_url_qianbu);
        et_url_weibu = view.findViewById(R.id.et_url_weibu);
        ll_url_item_add = view.findViewById(R.id.ll_url_item_add);
        ll_url_item_add.setOnClickListener(this);
        ll_item_store = view.findViewById(R.id.ll_item_store);
        tv_status = view.findViewById(R.id.tv_status);
        srl_film_add = view.findViewById(R.id.srl_film_add);
        srl_film_add.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (et_sid.getText().toString().equals("")) {
                    tv_status.setText("");
                } else {
                    aiv_douban_search.smoothToShow();
                    querySidExists(et_sid.getText().toString());
                    getFilmDetails(et_sid.getText().toString());
                }
                getAllLarge();
                getAllImageQuality();
            }
        });
    }

    private void initData() {
        getAllLarge();
        getAllImageQuality();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (!DataApplication.classificationAndImageQualityFlag) {
            nsv_film_add.scrollTo(0, 0);
            srl_film_add.autoRefresh();
            DataApplication.classificationAndImageQualityFlag = true;
        }
        bundle = getArguments();
        if (bundle != null && bundle.containsKey("sid")) {
            String sid = bundle.getString("sid");
            et_sid.setText(sid);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (bundle != null) {
            bundle.clear();
        }
    }

    //利用豆瓣ID获取影片详细信息
    private void getFilmDetails(String sid) {
        httpModel.getFilmDetails(sid, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Film film = (Film) data;

                HttpClient.handler.post(() -> {
                    et_film_name.setText(film.getName());
                    et_tag.setText(film.getTag());
                    et_post_url.setText(film.getPostUrl());
                    et_score.setText(film.getScore());
                    et_director.setText(film.getDirector());
                    et_scriptwriter.setText(film.getScriptwriter());
                    et_leading_role.setText(film.getLeadingRole());
                    et_production_country_or_region.setText(film.getProductionCountryOrRegion());
                    et_language.setText(film.getLanguage());
                    et_release_date.setText(film.getReleaseDate());
                    et_premiere.setText(film.getPremiere());
                    et_single_episode_length.setText(film.getSingleEpisodeLength());
                    et_number_of_seasons.setText(film.getNumberOfSeasons());
                    et_number_of_episode.setText(film.getNumberOfEpisode());
                    et_aka.setText(film.getAka());
                    et_plot.setText(film.getPlot());
                    if (film.getName() != null) {
                        et_pinyin_name.setText(Utils.toPinYin(film.getName()));
                    } else {
                        et_pinyin_name.setText("");
                    }
                    et_play_num.setText("0");
                    et_film_url.setText("");
                    nsv_film_add.scrollTo(0, 0);//ScrollView回到顶部
                    aiv_douban_search.smoothToHide();
                });
            }
        });
    }

    //获取所有大分类
    private void getAllLarge() {
        httpModel.getAllLarge(new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<LargeClassification> datas = Utils.<LargeClassification>objectToList(data);
                List<String> largeClassificationList = new ArrayList<>();
                for (LargeClassification largeClassification : datas) {
                    largeClassificationList.add(largeClassification.getClassification());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, R.layout.item_select, largeClassificationList);
                        sp_large_classification.setAdapter(arrayAdapter);
                        sp_large_classification.setSelection(0);
                        sp_large_classification.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                getAllRelatedSmallClassification(datas.get(position).getId());
                                getAllRelatedRegion(datas.get(position).getId());
                                getAllRelatedYear(datas.get(position).getId());
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                        srl_film_add.finishRefresh();
                    }
                });

            }
        });
    }

    //获取指定大分类id所关联的所有小分类
    public void getAllRelatedSmallClassification(int id) {
        httpModel.getAllRelatedSmallClassification(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<SmallClassification> datas = Utils.<SmallClassification>objectToList(data);
                List<String> smallClassificationList = new ArrayList<>();
                for (SmallClassification smallClassification : datas) {
                    smallClassificationList.add(smallClassification.getClassification());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, R.layout.item_select, smallClassificationList);
                        sp_small_classification.setAdapter(arrayAdapter);
                        sp_small_classification.setSelection(0);
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                        srl_film_add.finishRefresh();
                    }
                });
            }
        });
    }

    //获取指定大分类id所关联的所有地区
    public void getAllRelatedRegion(int id) {
        httpModel.getAllRelatedRegion(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<TheRegion> datas = Utils.<TheRegion>objectToList(data);
                List<String> theRegionList = new ArrayList<>();
                for (TheRegion theRegion : datas) {
                    theRegionList.add(theRegion.getTheRegion());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, R.layout.item_select, theRegionList);
                        sp_the_region.setAdapter(arrayAdapter);
                        sp_the_region.setSelection(0);
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                        srl_film_add.finishRefresh();
                    }
                });
            }
        });
    }

    //获取指定大分类id所关联的所有年份
    public void getAllRelatedYear(int id) {
        httpModel.getAllRelatedYear(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<TheYear> datas = Utils.<TheYear>objectToList(data);
                List<String> theYearList = new ArrayList<>();
                for (TheYear theYear : datas) {
                    theYearList.add(theYear.getTheYear());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, R.layout.item_select, theYearList);
                        sp_the_year.setAdapter(arrayAdapter);
                        sp_the_year.setSelection(0);
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                        srl_film_add.finishRefresh();
                    }
                });
            }
        });
    }

    //获取全部画质信息
    private void getAllImageQuality() {
        httpModel.getAllImageQuality(data -> {
            List<ImageQuality> datas = Utils.<ImageQuality>objectToList(data);
            List<String> imageQualityList = new ArrayList<>();
            for (ImageQuality imageQuality : datas) {
                imageQualityList.add(imageQuality.getImageQuality());
            }
            HttpClient.handler.post(() -> {
                arrayAdapter = new ArrayAdapter<>(context, R.layout.item_select, imageQualityList);
                sp_image_quality.setAdapter(arrayAdapter);
                sp_image_quality.setSelection(0);
                arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                srl_film_add.finishRefresh();
            });
        });
    }

    ////判读库中是否存在指定sid的影片
    private void querySidExists(String sid) {
        httpModel.querySidExists(sid, data -> {
            HttpClient.handler.post(() -> {
                if ((Boolean) data) {
                    tv_status.setText("库中已存在,无法添加");
                    tv_status.setTextColor(Color.parseColor("#FF596A"));
                } else {
                    tv_status.setText("库中不存在，可以添加");
                    tv_status.setTextColor(Color.parseColor("#00CD00"));
                }
            });
        });
    }

    //添加影片
    private void addFilm(Film film) {
        httpModel.addFilm(film, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            ToastUtil.show(context, "添加成功");
                            DataApplication.dataFlag = false;
                            if (!et_sid.getText().toString().equals("")) {
                                querySidExists(et_sid.getText().toString());
                            }
                        } else {
                            ToastUtil.show(context, "添加失败");
                        }
                        aiv_douban_search.smoothToHide();
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_add:
                if (et_film_name.getText().toString().equals("")) {
                    ToastUtil.show(context, "影片名称不能为空哦");
                } else {
                    if (et_film_url.getText().toString().equals("")) {
                        ToastUtil.show(context, "影片地址不能为空哦");
                    } else {
                        if (et_sid.getText().toString().equals("")) {
                            film.setSid(null);
                        } else {
                            if (tv_status.getText().toString().equals("库中已存在,无法添加")) {
                                ToastUtil.show(context, "库中已存在,无法添加");
                                return;
                            } else {
                                film.setSid(et_sid.getText().toString());
                            }
                        }
                        film.setName(et_film_name.getText().toString());
                        film.setPinYinName(et_pinyin_name.getText().toString());
                        film.setPostUrl(et_post_url.getText().toString());
                        film.setScore(et_score.getText().toString());
                        film.setReleaseDate(et_release_date.getText().toString());
                        film.setPlayNum(Integer.valueOf(et_play_num.getText().toString()));
                        film.setSingleEpisodeLength(et_single_episode_length.getText().toString());
                        film.setProductionCountryOrRegion(et_production_country_or_region.getText().toString());
                        if (sp_large_classification.getSelectedItemPosition() != -1) {
                            film.setLargeClassification(sp_large_classification.getSelectedItem().toString());
                        }
                        if (sp_small_classification.getSelectedItemPosition() != -1) {
                            film.setSmallClassification(sp_small_classification.getSelectedItem().toString());
                        }
                        if (sp_the_region.getSelectedItemPosition() != -1) {
                            film.setTheRegion(sp_the_region.getSelectedItem().toString());
                        }
                        if (sp_the_year.getSelectedItemPosition() != -1) {
                            film.setTheYear(sp_the_year.getSelectedItem().toString());
                        }
                        film.setTag(et_tag.getText().toString());
                        film.setDirector(et_director.getText().toString());
                        film.setScriptwriter(et_scriptwriter.getText().toString());
                        film.setLeadingRole(et_leading_role.getText().toString());
                        film.setLanguage(et_language.getText().toString());
                        film.setPremiere(et_premiere.getText().toString());
                        film.setNumberOfSeasons(et_number_of_seasons.getText().toString());
                        film.setNumberOfEpisode(et_number_of_episode.getText().toString());
                        film.setAka(et_aka.getText().toString());
                        film.setPlot(et_plot.getText().toString());
                        List<FilmUrl> filmUrlList = new ArrayList<>();
                        String numberOfEpisode = et_number_of_episode.getText().toString();
                        if (sp_image_quality.getSelectedItemPosition() != -1) {
                            String urlQianbu = et_url_qianbu.getText().toString();
                            String urlWeibu = et_url_weibu.getText().toString();
                            if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                                Type listOfMyClassObject = new TypeToken<ArrayList<EpisodeUrl>>() {
                                }.getType();
                                List<EpisodeUrl> outputList = gson.fromJson(et_film_url.getText().toString(), listOfMyClassObject);

                                FilmUrl filmUrl = new FilmUrl(sp_image_quality.getSelectedItem().toString(), outputList);
                                filmUrlList.add(filmUrl);
                            } else {
                                EpisodeUrl episodeUrl = new EpisodeUrl(sp_image_quality.getSelectedItem().toString(), et_film_url.getText().toString());
                                List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                                episodeUrlList.add(episodeUrl);
                                FilmUrl filmUrl = new FilmUrl(sp_image_quality.getSelectedItem().toString(), episodeUrlList);
                                filmUrlList.add(filmUrl);
                            }

                        }

                        for (int i = 0; i < spinners.size(); i++) {
                            if (spinners.get(i).getSelectedItemPosition() != -1) {
                                if (editTexts.get(i).getText().toString().equals("")) {
                                    ToastUtil.show(context, "影片地址不能为空哦");
                                    return;
                                } else {
                                    View child = ll_item_store.getChildAt(i + 1);
                                    EditText et_url_qianbu_item = child.findViewById(R.id.et_url_qianbu_item);
                                    EditText et_url_weibu_item = child.findViewById(R.id.et_url_weibu_item);
                                    String urlQianbu = et_url_qianbu_item.getText().toString();
                                    String urlWeibu = et_url_weibu_item.getText().toString();
                                    if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                                        Type listOfMyClassObject = new TypeToken<ArrayList<EpisodeUrl>>() {
                                        }.getType();
                                        List<EpisodeUrl> outputList = gson.fromJson(editTexts.get(i).getText().toString(), listOfMyClassObject);
                                        FilmUrl filmUrl = new FilmUrl(spinners.get(i).getSelectedItem().toString(), outputList);
                                        filmUrlList.add(filmUrl);
                                    } else {
                                        EpisodeUrl episodeUrl = new EpisodeUrl(spinners.get(i).getSelectedItem().toString(), editTexts.get(i).getText().toString());
                                        List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                                        episodeUrlList.add(episodeUrl);
                                        FilmUrl filmUrl = new FilmUrl(spinners.get(i).getSelectedItem().toString(), episodeUrlList);
                                        filmUrlList.add(filmUrl);
                                    }
                                }
                            }
                        }

                        String filmUrlJson = gson.toJson(filmUrlList);
                        film.setFilmUrl(filmUrlJson);
                        aiv_douban_search.smoothToShow();
                        addFilm(film);
                    }
                }
                break;
            case R.id.ll_url_quick_add:
                String numberOfEpisode = et_number_of_episode.getText().toString();
                String urlQianbu = et_url_qianbu.getText().toString();
                String urlWeibu = et_url_weibu.getText().toString();
                if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                    int episodeNum = Integer.parseInt(numberOfEpisode);
                    List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                    for (int i = 1; i < episodeNum + 1; i++) {
                        String url = urlQianbu + i + urlWeibu;
                        String episode = i + "";
                        EpisodeUrl episodeUrl = new EpisodeUrl(episode, url);
                        episodeUrlList.add(episodeUrl);
                    }
                    String episodeJson = gson.toJson(episodeUrlList);
                    et_film_url.setText(episodeJson);
                }
                break;
            case R.id.ll_url_item_add:
                View customView = LayoutInflater.from(context).inflate(R.layout.film_url_add_item, ll_item_store, false);

                Spinner sp_image_quality_item = customView.findViewById(R.id.sp_image_quality_item);
                sp_image_quality_item.setAdapter(arrayAdapter);
                sp_image_quality_item.setSelection(0);

                EditText et_film_url_item = customView.findViewById(R.id.et_film_url_item);
                EditText et_url_qianbu_item = customView.findViewById(R.id.et_url_qianbu_item);
                EditText et_url_weibu_item = customView.findViewById(R.id.et_url_weibu_item);
                LinearLayout ll_url_quick_add_item = customView.findViewById(R.id.ll_url_quick_add_item);

                ll_item_store.addView(customView);
                spinners.add(sp_image_quality_item);
                editTexts.add(et_film_url_item);

                ll_url_quick_add_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String numberOfEpisode = et_number_of_episode.getText().toString();
                        String urlQianbu = et_url_qianbu_item.getText().toString();
                        String urlWeibu = et_url_weibu_item.getText().toString();
                        if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                            int episodeNum = Integer.parseInt(numberOfEpisode);
                            List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                            for (int i = 1; i < episodeNum + 1; i++) {
                                String url = urlQianbu + i + urlWeibu;
                                String episode = i + "";
                                EpisodeUrl episodeUrl = new EpisodeUrl(episode, url);
                                episodeUrlList.add(episodeUrl);
                            }
                            String episodeJson = gson.toJson(episodeUrlList);
                            et_film_url_item.setText(episodeJson);
                        }
                    }
                });

                LinearLayout ll_delete = customView.findViewById(R.id.ll_delete);
                ll_delete.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int index = ll_item_store.indexOfChild(customView);
                        ll_item_store.removeView(ll_item_store.getChildAt(index));
                        spinners.remove(index - 1);
                        editTexts.remove(index - 1);
                        return true;
                    }
                });
                break;
        }
    }
}